
class watcher{
    constructor(vm,expr,cb){
        this.vm = vm;
        this.expr = expr;
        this.cb = cb;
        // 先把旧值保存起来
        this.oldval = this.getOldValue()
    }
    getOldValue(){
        Dep.target = this;
        const oldval = compileUtil.getVal(this.expr,this.vm)
        Dep.target = null
        return oldval
    }
    update() {
        const newVal = compileUtil.getVal(this.expr,this.vm)
        if(newVal !== this.oldval){
            this.cb(newVal)
        }   
    }
}

class Dep{
    constructor(){
        this.subs = [];
    }
    //收集观察者
    addSub(watcher){
        this.subs.push(watcher)
    }
    //通知观察者去更新
    notify(){
        console.log('通知了观察者',this.subs)
        this.subs.forEach(w=>w.update())
    }
}


class Observer{
    constructor(data){
        this.observer(data);
    }
    observer(data){
        /*
           person: {
                msg:'121',
                fav:{
                    name:2323
                }
            }
        
        */
       if(data && typeof data === 'object'){
           Object.keys(data).forEach(key =>{
               this.defineReactive(data,key,data[key])
           })
       }
    }
    defineReactive(data,key,value){
        //递归遍历
        this.observer(value);
        const dep = new Dep()
        //劫持并监听所有的属性
        Object.defineProperty(data,key,{
            enumerable:true,
            configurable:false,
            get(){
                // 初始化
                // 订阅数据变化是，往dep中增加观察者；
                Dep.target && dep.addSub(Dep.target)
                return value;
            },
            set:(newVal)=>{
                this.observer(newVal)
                if(newVal !== value){
                    value = newVal;
                }
                //告诉Dep通知变化
                dep.notify();
            }
        })
    }
}